import axios from 'axios';

class Api {
    server;
    constructor(host) {
        this.server = axios.create({
            baseURL: host,
            timeout: 3000,
            withCredentials: false,
            headers: {
                'X-Custom-Header': 'foobar'
            }
        });
        this.server.interceptors.request.use((config) => {
            if (config.data instanceof FormData) {
                config.headers = {
                    ...config.headers,
                    'Content-Type': 'multipart/form-data'
                };
            }
            return config;
        }, function (err) {
            return Promise.reject(err);
        });
        this.server.interceptors.response.use((response) => {
            return response;
        }, function (err) {
            return Promise.reject(err);
        })
    }

    RequestApi(method = 'get', url, body) {
        if (method === 'get' || method === 'delete') {
            body = ''
        };
        const data = async (resolve, reject) => {
            try {
                const result = await this.server({
                    method: method,
                    url: url,
                    data: body
                });
                resolve(result.data);
            } catch (err) {
                reject(err.toString());
            }
        }

        return new Promise(data);
    }
}
const request = new Api('http://localhost:3000/api');
export default request;